//
//  CloudApiService.swift
//  Health-Doctor
//
//  Created by woniu on 2025/7/18.
//  Copyright © 2025 掌上卫健. All rights reserved.
//

import Foundation

enum CloudSearchEnum: String {
    case kBH = "bh"
    case kName = "xm"
    case kIDCard = "zjhm"
}

class CloudApiService: NSObject {
    static let shared = CloudApiService()
    
    public var appId = "e860a5a1a6a940b49be5637cbe60181c"
    public var uuid = ""
    public var code = ""
    public var sid = ""
    public var token = ""
    public var areaId = ""
    public var orgId = ""
    //登录太频繁，需要图形验证码
    public var imageCodeKey = ""
    public var imageCodeValue = ""
    public var userAgentString = ""
    //获取到档案详情数据回调
    private var onGetArchivesDetailBlock: ((_ re:Bool,_ data:[String:Any])->())?
    //当登录成功后调用的代码块
    public var onLoginSuccessBlock: (()->())?
    //获取云平台家庭档案列表
    private var onGetFamilyListBlock: ((_ re:Bool,_ data:[[String:Any]])->())?
    //我们档案的身份证对应云平台档案ID
    private var woniuIDCardToCloudDataIdDic:[String:String] = [:]
    //登录失效，自动重新登录次数
    private var reLoginCount = 0
    //搜索失败自动搜索次数
    private var reSearchArchivesCount = 0
    private var reSearchFamilyCount = 0
    private var reSaveArchivesCount = 0
    //是否正在现在图形验证码
    private var isShowingAuthAlert = false
    private override init() {
        self.uuid = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
        LogUtil.print(info: "uuid=\(self.uuid)")
    }
    
    
    public func getIpAddress()->String{
        let domain = getDomain()
//        if UrlConfigItem.isOnline(){
            return "https://\(domain)"
//        }
//        return "http://\(domain):99"
    }
    
    private func getDomain()->String{
//        if UrlConfigItem.isOnline(){
            return "ehr.scwjxx.cn"
//        }
//        return "223.85.21.172"
    }
    
    
    /// 日志记录
    /// - Parameter log: 日志信息
    public func printWrite(log:String){
        LogUtil.print(info: "打印：")
        YBLog(log)
        
    }
    
    //重新登录
    public func reAutoLogin(){
        self.printWrite(log: "云平台网页接口，开始重新登录")
        
    }
    
    //通过身份证/档案编号获取云平台档案ID
    public func getCloudRhrIdBy(searchKey:String)->String{
        let dataId = self.woniuIDCardToCloudDataIdDic[searchKey] ?? ""
        return dataId
    }
    
    //缓存云平台档案ID,searchKey:身份证或档案编号
    public func cacheCloudArchivesDataIdBy(searchKey:String,cloudDataId:String){
        self.woniuIDCardToCloudDataIdDic[searchKey] = cloudDataId
    }
    
    /// 跳转到绑定云平台账号页面
    private func bindCloudAccount(){
        self.onLoginSuccessBlock = nil
        MyMessage.showText(message: "请绑定云平台账号")
       
    }
    
    //登录过期
    public func isLoginExpiry(msg:String)->Bool{
        if msg.contain("其他地方登录") || msg.contain("登录过期") || msg.contain("重新登录") || msg.contain("未登录") ||  msg.contain("被挤出") || msg.contain("请先登录"){
            return true
        }
        return false
    }
    
    
    /// 密码错误
    public func isPasswordError(msg:String)->Bool{
        return msg.contain("密码错误")
    }
    
    /// 调用接口出错弹框
    /// - Parameters:
    ///   - msg: 云平台接口错误
    ///   - httpCode: 状态码
    public func alertOnError(msg:String,httpCode:Int){
        
        
        DispatchQueue.main.async {
            //
            MyMessage.showText(message: msg)
            
            if self.isPasswordError(msg: msg){
                self.printWrite(log: "密码错误(\(msg))，可能密码已被修改，提醒用户需要重新绑定")
                
                
                //不提示，自动登录
            }else if self.isLoginExpiry(msg: msg) == true{
                //清除缓存
                self.clearToken()
                
                if self.reLoginCount < 3{
                    self.reLoginCount += 1
                    self.printWrite(log: "登录失效，准备自动重新登录(error:\(msg))，reLoginCount:\(self.reLoginCount)")
                    self.reAutoLogin()
                }else{
                    self.printWrite(log: "登录失效，弹框提醒是否需要重新登录，error:\(msg)")
                   
                }
                //真实存在登录太平凡后，需要输入验证码
            }else if msg.contain("输入图形验证码") || msg.contain("图形验证码输入错误"){
                //防止多个接口并发验证
                if self.isShowingAuthAlert{return}
//                
//                self.httpGetImageCode {[weak self] re, key, imgBase64 in
//                    if re{
//                        self?.isShowingAuthAlert = true
//                        let alert = ImgAuthAlert()
//                        alert.onDismisBlock = {[weak self]in
//                            guard let `self` = self else { return }
//                            self.isShowingAuthAlert = false
//                        }
//                        alert.showFromCloud(title:msg,codeKey:key,imgBase64: imgBase64) {[weak self] codeKey,imgCode in
//                            guard let `self` = self else { return }
//                            self.imageCodeKey = codeKey
//                            self.imageCodeValue = imgCode
//                            LogUtil.print(info: "图形验证码是:\(imgCode)")
//                            self.reAutoLogin()
//                        }
//                    }
//                }
            }
            
        }
    }
    
    // 清除缓存，下次使用需要重新登录
    private func clearToken(){
        self.printWrite(log: "清除缓存clearToken()")
        self.code = ""
        self.sid = ""
        self.token = ""
        self.areaId = ""
        self.orgId = ""
        self.imageCodeKey = ""
        self.imageCodeValue = ""
        self.woniuIDCardToCloudDataIdDic.removeAll()
    }
    
    //获取header指定内容
    public func getUserAgent()->String{
        if !userAgentString.isEmpty{
            return userAgentString
        }
        let kUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_7) AppleWebKit/604.1.15 (KHTML, like Gecko) Version/16.5 Safari/604.1.15"
        let kUserAgent0 = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.34 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/131.0.0.0"
        let kUserAgent1 = "Mozilla/5.1 (Windows NT 9.0; Win64; x64) AppleWebKit/600.1.15 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/517.36 Edg/131.0.0.0"
        let kUserAgent2 = "Mozilla/5.0 (Windows NT 9.7; Win64; x64) AppleWebKit/517.31 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/527.36 Edg/131.0.0.0"
        let kUserAgent3 = "Mozilla/5.3 (Windows NT 10.0; Win64; x64) AppleWebKit/603.1.15 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/517.36 Edg/131.0.0.0"
        let kUserAgent4 = "Mozilla/5.0 (Windows NT 12.0; Win64; x64) AppleWebKit/535.35 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/527.36 Edg/131.0.0.0"
        let kUserAgent5 = "Mozilla/4.9 (Windows NT 11.0; Win64; x64) AppleWebKit/605.1.15 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/536.36 Edg/131.0.0.0"
        let arr:[String] = [kUserAgent,kUserAgent0,kUserAgent1,kUserAgent2,kUserAgent3,kUserAgent4,kUserAgent5]
        let random = arc4random() % UInt32(arr.count)
        userAgentString = arr[Int(random)]
        return userAgentString
    }
    
    //获取header指定key内容
    public func getAgbBatbaBbabString()->String{
        var agbBatbaBbabArr:[String] = []
        agbBatbaBbabArr.append("IP38ymTYKeT4YVIkbP9BW0iw02I1wTZMumkW+RtmH3bpDEXoASgK6YUbsP4J2dz5+7VRzzdtt73oTQK7XZbyUaYtUXQO7bSCABS+7qHIv2wHOa5Ysyyj3BOJXIo3nVJyimSayJgsYkjllnRmaDuX0mwnw/50lbCKnxNfwnv5tlu9WF8GaD2aEV04+HX+xvikork7/4vgyXd8lT9Lrg90gzJMH5CCQRU4toLJ9k2I5so=")
        agbBatbaBbabArr.append("bi88zwJCIkxSlso6lUAjpssy26TU37eGnfQrl92CRvKg38OZMYb6LniqNaHrnFiDZu4cBklk7Xd+1GlXiycbiDmwa8D5Audh9JbArmtzTpnEF5ZS+Y5yaY4j2bUXYm2qOlhMrjwQVtd2vmrlJY18eQyoSGlluBJCfW1gZSVM+ZrNpEbE2dTVRHfBwCZPXLHLc7ichE1WM4YCvhMCnHSoTaDQDoevJFEPLXQilMfSY24=")
        
        let random = arc4random()%10
        if random % 2 == 0{
            return agbBatbaBbabArr.first!
        }
        return agbBatbaBbabArr.last!
    }
    
}

extension CloudApiService{
    
    ///  获取家庭详情
    /// - Parameters:
    ///   - dataId: 家庭ID
    public func httpGetCloudFamilyDetail(dataId:String,onFinishBlock: @escaping ((_ re:Bool,_ familyDetail:[String:Any])->())){
        let queryBlock = {
            self.apiGetFamilyDetail(dataId: dataId, token: self.token, uuid: self.uuid, sid: self.sid, finish: onFinishBlock)
        }
        if sid.isEmpty || code.isEmpty || token.isEmpty{
            self.printWrite(log: "准备查询家庭档案详情，发现未登录，去登录")
            self.onLoginSuccessBlock = queryBlock
            self.reAutoLogin()
        }else{
            queryBlock()
        }
    }
    
    
    /// 转码=》把云平台的家庭列表转换两只蜗牛家庭档案列表（使用场景，编辑档案时切换家庭，通过网页接口搜索云平台档案后，需要把该家庭档案详情数据转换成蜗牛格式的数据再交给H5显示）
    /// - Parameters:
    ///   - woniuArchives: 蜗牛档案数据
    public func httpFamilyCloudToLocalStyle(cloudFamil:[String:Any],finish:((_ re:Bool,_ localFamily:[String:Any])->())?){
        let action = ArchivesAction.cloudFamilyToLocalFamily(param: cloudFamil)
        MyMessage.showWaitHUD()
        archivesProvider.httpRequst(action) { result in
            MyMessage.hiddenWaitHUD()
            if result.isSuccess(){
                let localFamily = result.dicData()
                finish?(true,localFamily)
            }else{
                MyMessage.showText(message: result.msg)
                finish?(false,[:])
            }
        }
    }
    
    
    
}



//该业务层供外界调用，该层内部调用api核心层。
extension CloudApiService{
    
    
    /// 缓存云平台档案到两只蜗牛
    /// - Parameters:
    ///   - data: 云平台档案的详情数据
    ///   - finish: 返回两只蜗牛的档案ID
    public func httpCacheArchivesToWoniu(cloudArchives:[String:Any],finish:((_ re:Bool,_ rhrId:String)->())?){
        let action = ArchivesAction.cacheCloudArchivesToWoniu(param:cloudArchives)
        MyMessage.showWaitHUD()
        archivesProvider.httpRequst(action) { result in
            MyMessage.hiddenWaitHUD()
            if result.isSuccess(){
                let rhrId =  result.getStringData()
                finish?(true,rhrId)
            }else{
                MyMessage.showText(message: result.msg)
                finish?(false,"")
            }
        }
    }
    
    
    /// 转码=》把两只蜗牛的个人档案数据转云平台的档案数据（使用场景，编辑个人档案保存时，需要把两只蜗牛页面数据和云平台档案详情结合后，通过云平台数据结构一起保存到云平台）
    /// - Parameters:
    ///   - woniuArchives: 蜗牛档案数据
    public func httpLocalToCloudStyle(localArchives:[String:Any],cloudArchives:[String:Any],finish:((_ re:Bool,_ cloudData:[String:Any])->())?){
        let action = ArchivesAction.changeSubmitWCDataStyle(param: ["remoteArchives":cloudArchives,"localArchives":localArchives])
        MyMessage.showWaitHUD()
        archivesProvider.httpRequst(action) { result in
            MyMessage.hiddenWaitHUD()
            if result.isSuccess(){
                let cloudData = result.dicData()
                finish?(true,cloudData)
            }else{
                MyMessage.showText(message: result.msg)
                finish?(false,[:])
            }
        }
    }
    
    
    /// 获取云平台档案ID
    /// - Parameters:
    ///   - searchKey: 身份证或者编号
    ///   - searchType: 搜索类型
    ///   - rhrStatus: 档案状态
    ///   - onFinishBlock: 回调
    public func httpGetWebRhrId(searchKey:String,searchType:CloudSearchEnum,rhrStatus:Int?,onFinishBlock: @escaping ((_ re:Bool,_ cloudRhrId:String)->())){
        let rhrId = getCloudRhrIdBy(searchKey: searchKey)
        if !rhrId.isEmpty{
            onFinishBlock(true,rhrId)
            return
        }
        let searchBlock = {
            self.apiSearchArchivesListItem(sid: self.sid, token: self.token, uuid: self.uuid, areaId: self.areaId, searchKey: searchKey, searchType: searchType, rhrStatus: rhrStatus) { re, listItem in
                if re{
                    let rhrId = listItem.strValue("daId")
                    onFinishBlock(true,rhrId)
                }else{
                    onFinishBlock(false,"")
                }
            }
        }
        if sid.isEmpty || code.isEmpty || token.isEmpty{
            self.printWrite(log: "通过关键词搜索个人档案摘要获取档案ID,searchKey:\(searchKey) searchType:\(searchType.rawValue)，发现未登录，去登录")
            self.onLoginSuccessBlock = searchBlock
            self.reAutoLogin()
        }else{
            searchBlock()
        }
    }
    
    /// =============通过编号/身份证去云平台搜索，返回档案详情数据
    /// - Parameter searchKey: 云平台数据编号、身份证
    public func httpSearchArchivesDetailBy(searchKey:String,searchType:CloudSearchEnum,rhrStatus:Int?,onFinishBlock: @escaping ((_ re:Bool,_ archivesDetail:[String:Any])->())){
        self.onGetArchivesDetailBlock = onFinishBlock
        
        let searchBlock = {
            //搜索档案列表
            self.apiSearchArchivesListItem(sid: self.sid, token:self.token, uuid: self.uuid, areaId: self.areaId, searchKey: searchKey, searchType:searchType,rhrStatus: rhrStatus) {[weak self] re, listItem in
                guard let `self` = self else { return }
                if re{
                    let daId = listItem.strValue("daId")
                    //查询档案详情
                    if self.onGetArchivesDetailBlock != nil{
                        self.apiGetDetail(dataId: daId, orgId: self.orgId, token: self.token, uuid: self.uuid, sid: self.sid)
                    }
                    
                }else{
                    onFinishBlock(false,[:])
                }
            }
        }
        if sid.isEmpty || code.isEmpty || token.isEmpty{
            self.printWrite(log: "通过关键词拉取个人档案详情searchKey:\(searchKey) searchType:\(searchType.rawValue)，发现未登录，去登录")
            //登录成功后自动开始搜索
            self.onLoginSuccessBlock = searchBlock
            self.reAutoLogin()
        }else{
            searchBlock()
        }
    }
    
    
    /// 通过云平台的dataId保存数据
    /// - Parameters:
    ///   - woniuArchives:  两只蜗牛格式的居民档案
    ///   - localJtId: 档案修改前的家庭id
    ///   - cloudArchivesDetail: 该档案在云平台的详情数据（提交给后端进行合并）
    ///   - remoteJtId: 切换家庭后，该家庭在云平台真正的id(只能通过授权接口才能拿到，网页接口拿不到的，网页接口拿到是动态的)，不修改家庭时传空
    ///   - onFinishBlock:
    public func httpSaveArchivesToCloudBy(woniuArchives:[String:Any],localJtId:String,cloudArchivesDetail:[String:Any],remoteJtId:String,onFinishBlock: @escaping ((_ re:Bool,_ cloudData:[String:Any])->())){
        let saveBlock = {[weak self]in
            guard let `self` = self else { return }
            let collaborativeContentId = woniuArchives.strValue("collaborativeContentId")
            //数据转码，把蜗牛数据格式 + 云平台档案详情 => 云平台网页接口数据格式（进行合并保存）
            self.httpLocalToCloudStyle(localArchives: woniuArchives, cloudArchives: cloudArchivesDetail) {[weak self] reV2, cloudStyleData in
                guard let `self` = self else { return }
                if reV2{
                    //通过云平台网页接口提交到云平台
                    self.apiSaveArchivesToCloud(params: cloudStyleData, token: self.token, uuid: self.uuid, sid: self.sid) {[weak self] rev3 in
                        guard let `self` = self else { return }
                        if rev3{
                            var submitClooudData = cloudStyleData
                            //若存协作组进去编辑档案，需要继续传进去
                            if !collaborativeContentId.isEmpty{
                                submitClooudData["collaborativeContentId"] = collaborativeContentId
                            }
                            submitClooudData["localJtId"] = localJtId
                            if !remoteJtId.isEmpty{
                                submitClooudData["remoteJtId"] = remoteJtId
                            }
                            //把云平台格式数据 保存到两只蜗牛
                            self.httpCacheArchivesToWoniu(cloudArchives: submitClooudData) { reV4, rhrId in
                                if reV4{
                                    onFinishBlock(true,cloudStyleData)
                                }else{
                                    onFinishBlock(false,[:])
                                }
                            }
                        }else{
                            onFinishBlock(false,[:])
                        }
                    }
                    
                }else{
                    onFinishBlock(false,[:])
                }
            }
        }
        
        //报错了就重新登录
        if sid.isEmpty || code.isEmpty || token.isEmpty{
            self.printWrite(log: "编辑个人档案保存时，发现未登录，去登录")
            self.onLoginSuccessBlock = saveBlock
            self.reAutoLogin()
            
        }else{
            saveBlock()
        }
    }
    
    
    /// 搜索家庭列表
    /// - Parameters:
    ///   - searchKey: 关键词
    ///   - searchType: 搜索类型
    public func httpGetCloudFamilyList(searchKey:String,searchType:CloudSearchEnum,onFinishBlock: @escaping ((_ re:Bool,_ familyList:[[String:Any]])->())){
        let queryBlock = {
            self.apiGetFamilyList(token: self.token, uuid: self.uuid, sid: self.sid,areaId: self.areaId, searchKey: searchKey, searchType: searchType,finish: onFinishBlock)
        }
        if sid.isEmpty || code.isEmpty || token.isEmpty{
            self.printWrite(log: "通过关键词搜索家庭档案列表searchKey:\(searchKey) searchType:\(searchType.rawValue)，发现未登录，去登录")
            self.onLoginSuccessBlock = queryBlock
            self.reAutoLogin()
            
        }else{
            queryBlock()
        }
    }
    
    
    /// 转码=》把云平台的家庭列表转换两只蜗牛家庭档案详情（使用场景，编辑档案时切换家庭，通过网页接口搜索云平台档案后展示数据）
    /// - Parameters:
    ///   - woniuArchives: 蜗牛档案数据
    public func httpFamilyListCloudToLocalStyle(cloudFamilList:[[String:Any]],finish:((_ re:Bool,_ localFamilyList:[[String:Any]])->())?){
        let action = ArchivesAction.cloudFamilyListToLocalList(param: ["familyList":cloudFamilList])
        MyMessage.showWaitHUD()
        archivesProvider.httpRequst(action) { result in
            MyMessage.hiddenWaitHUD()
            if result.isSuccess(){
                let list = result.getListData()
                finish?(true,list)
            }else{
                MyMessage.showText(message: result.msg)
                finish?(false,[])
            }
        }
    }
    
    
    /// 获取图片验证码信息
    public func httpGetImageCode(finish:@escaping((_ re:Bool,_ key:String,_ imgBase64:String)->())) {
        self.apiGetImageCode(appId: self.appId, uuid: self.uuid, finish: finish)
    }
}


//该模块直接调用云平台接口
extension CloudApiService{
    
    
    /// 根据档案编号、证件号搜索档案详情
    /// - Parameters:
    ///   - sid:
    ///   - token:
    ///   - uuid:
    ///   - areaId: 区划
    ///   - searchKey: 关键词
    ///   - searchType: 搜索类型
    ///   - rhrStatus: 状态
    private func apiSearchArchivesListItem(sid:String,token:String,uuid:String,areaId:String,searchKey:String,searchType:CloudSearchEnum,rhrStatus:Int?,finish:@escaping((_ re:Bool,_ listItem:[String:Any])->())) {
        if sid.isEmpty || token.isEmpty || areaId.isEmpty{
            self.reAutoLogin()
            return
        }
        let log = "开始搜索居民档案searchType:\(searchType.rawValue),searchKey:\(searchKey)"
        self.printWrite(log: log)
        let ipAddress = getIpAddress()
        let urlString = "\(ipAddress)/ehrc/ehr/jkda/get/paging/simple"
        guard var urlComponents = URLComponents(string: urlString) else{
            return
        }
        let queryItems = [
            URLQueryItem(name: "total", value: "1"),
            URLQueryItem(name: "pageNumber", value: "1"),
            URLQueryItem(name: "current", value: "1"),
            URLQueryItem(name: "pageSize", value: "14"),
            URLQueryItem(name: "area", value: ""),
            URLQueryItem(name: "areaId", value: areaId),
            URLQueryItem(name: "rbh", value: areaId),
            URLQueryItem(name: "qhId", value: areaId),
            URLQueryItem(name: "keyword", value: searchKey),
            URLQueryItem(name: "daztCode", value: "10"),
            URLQueryItem(name: "qyCsConditionCondition", value: "="),
            URLQueryItem(name: "keywordType", value: searchType.rawValue),
            URLQueryItem(name: "zrysIds", value: ""),
            URLQueryItem(name: "nlBeginType", value: "年"),
            URLQueryItem(name: "nlEndType", value: "年")
        ]
        
        urlComponents.queryItems = queryItems
        
        guard let url = urlComponents.url else {
            print("Invalid URL")
            return
        }
        
        // 创建请求
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        
        // 设置请求头
        request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
        request.setValue("gzip, deflate, br", forHTTPHeaderField: "Accept-Encoding")
        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        request.setValue(token, forHTTPHeaderField: "accessToken")
        request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.setValue("mK1M3eVPK1qtJOdv", forHTTPHeaderField: "Gnj-Whsti-Enji")
        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
        request.setValue("\(ipAddress)/jkda.html", forHTTPHeaderField: "Referer")
        request.setValue("empty", forHTTPHeaderField: "Sec-Fetch-Dest")
        request.setValue("cors", forHTTPHeaderField: "Sec-Fetch-Mode")
        request.setValue("same-origin", forHTTPHeaderField: "Sec-Fetch-Site")
        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        
        let domain = getDomain()
        // 设置 Cookie
        let cookieProperties: [HTTPCookiePropertyKey: Any] = [
            .name: "token",
            .value: token,
            .domain: domain,
            .path: "/"
        ]
        
        let cookieProperties2: [HTTPCookiePropertyKey: Any] = [
            .name: "sid",
            .value: sid,
            .domain: domain,
            .path: "/"
        ]
        
        let cookieProperties3: [HTTPCookiePropertyKey: Any] = [
            .name: "HWWAFSESID",
            .value: "fd03f76d9cc6b7a7b5",
            .domain: domain,
            .path: "/"
        ]
        
        let cookieProperties4: [HTTPCookiePropertyKey: Any] = [
            .name: "HWWAFSESTIME",
            .value: "1753060964188",
            .domain: domain,
            .path: "/"
        ]
        
        let cookieProperties5: [HTTPCookiePropertyKey: Any] = [
            .name: "uuid",
            .value: uuid,
            .domain: domain,
            .path: "/"
        ]
        
        if let cookie = HTTPCookie(properties: cookieProperties),
           let cookie2 = HTTPCookie(properties: cookieProperties2),
           let cookie3 = HTTPCookie(properties: cookieProperties3),
           let cookie4 = HTTPCookie(properties: cookieProperties4),
           let cookie5 = HTTPCookie(properties: cookieProperties5) {
            HTTPCookieStorage.shared.setCookie(cookie)
            HTTPCookieStorage.shared.setCookie(cookie2)
            HTTPCookieStorage.shared.setCookie(cookie3)
            HTTPCookieStorage.shared.setCookie(cookie4)
            HTTPCookieStorage.shared.setCookie(cookie5)
        }
        
        request.writeToLogFile()
        
        // 创建并启动任务
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: request) {[weak self] data, response, error in
            MyMessage.hiddenWaitHUD()
            guard let `self` = self else { return }
            
            DispatchQueue.main.async {
                
                guard let data = data else{
                    if self.reSearchArchivesCount < 1{//重试一次
                        self.printWrite(log: "搜索居民列表请求获取数据为空，自动重试一次")
                        self.reSearchArchivesCount += 1
                        self.apiSearchArchivesListItem(sid: self.sid, token: self.token, uuid: self.uuid, areaId: self.areaId, searchKey: searchKey, searchType: searchType, rhrStatus: rhrStatus,finish: finish)
                    }else{
                        MyMessage.showText(message: "请求失败，请重试")
                    }
                    return
                }
                
                if let responseString = String(data: data, encoding: .utf8) {
                    self.printWrite(log: "搜索居民档案list接口返回->\(responseString)")
                    let dic = responseString.toDic()
                    let httpCode = dic.intValue("code")
                    
                    if httpCode == 200{
                        let dataDic = dic.dictionary("data")
                        let dataArray = dataDic.array("data")
                        LogUtil.print(info: "查询到数据")
                        YBLog(dataArray)
                        
                        //缓存
                        for item in dataArray{
                            let idCard = item.strValue("zjhm")
                            let dataId = item.strValue("daId")
                            if idCard.isIDCardNum(){
                                self.cacheCloudArchivesDataIdBy(searchKey: searchKey, cloudDataId: dataId)
                            }
                        }
                        
                        //只有一条数据
                        if dataArray.count == 1{
                            let dataId = dataArray.first?.strValue("daId") ?? ""
                            self.cacheCloudArchivesDataIdBy(searchKey: searchKey, cloudDataId: dataId)
                            finish(true,dataArray.first!)
                            
                        }else if dataArray.count > 1{
                            //多条数据
                            var findItem:[String:Any] = dataArray.first!
                            //通过状态来过滤
                            let locStatus = rhrStatus ?? 0
                            for item in dataArray{
                                let cloudStatus = item.strValue("tcglYy")
                                if locStatus == UserStatusEnum.kNomarl.rawValue && cloudStatus == CloudArchivesStatusEnum.kNomarl.rawValue{
                                    findItem = item
                                    break
                                }
                                if locStatus == UserStatusEnum.kLose.rawValue && cloudStatus == CloudArchivesStatusEnum.kLose.rawValue{
                                    findItem = item
                                    break
                                }
                                if locStatus == UserStatusEnum.kDeath.rawValue && cloudStatus == CloudArchivesStatusEnum.kDeath.rawValue{
                                    findItem = item
                                    break
                                }
                                if locStatus == UserStatusEnum.kMoveOut.rawValue && cloudStatus == CloudArchivesStatusEnum.kMoveOut.rawValue{
                                    findItem = item
                                    break
                                }
                                if locStatus == UserStatusEnum.kSignOut.rawValue && cloudStatus == CloudArchivesStatusEnum.kSignOut.rawValue{
                                    findItem = item
                                    break
                                }
                            }
                            
                            let dataId = findItem.strValue("daId")
                            if !dataId.isEmpty{
                                self.cacheCloudArchivesDataIdBy(searchKey: searchKey, cloudDataId: dataId)
                                finish(true,findItem)
                            }
                        }else{
                            MyMessage.showText(message: "未搜索到该档案，请确认是否被删除")
                        }
                    }else{
                        let httpErrorMsg = dic.strValue("message")
                        if self.isLoginExpiry(msg: httpErrorMsg) == true{
                            let log = "搜索案接口apiSearchArchivesListItem发现登录过期 error:\(httpErrorMsg)）准备重新登录，登录成功后需重新调用该接口"
                            self.printWrite(log: log)
                            self.onLoginSuccessBlock = {[weak self]in
                                guard let `self` = self else { return }
                                self.apiSearchArchivesListItem(sid: self.sid, token: self.token, uuid: self.uuid, areaId: self.areaId, searchKey:searchKey, searchType: searchType, rhrStatus: rhrStatus,finish: finish)
                            }
                        }
                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
                    }
                }
            }
            
        }
        task.resume()
    }
    
    
    /// 获取档案详情
    /// - Parameters:
    ///   - dataId: 数据ID
    ///   - orgId: 机构ID
    ///   - token: TOKEN
    ///   - uuid:
    ///   - sid:
    private func apiGetDetail(dataId:String,orgId:String,token:String,uuid:String,sid:String) {
        LogUtil.print(info: "开始查询详情数据")
        let ipAddress = getIpAddress()
        let urlString = "\(ipAddress)/ehrc/ehr/jkda/get/\(dataId)?"
        guard let url = URL(string: urlString) else {
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        
        // Set headers
        request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
        request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.setValue(getAgbBatbaBbabString(), forHTTPHeaderField: "Agb-Batba-Bbab")
        request.setValue("", forHTTPHeaderField: "accessToken2")
        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        request.setValue("\(ipAddress)/index.html", forHTTPHeaderField: "Referer")
        request.setValue("KZEiL1Fncf64VB2N", forHTTPHeaderField: "E5o-Vt3gb-1aom")
        request.setValue(token, forHTTPHeaderField: "accessToken")
        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
        request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
        request.setValue("token=\(token); sid=\(sid); uuid=\(uuid)", forHTTPHeaderField: "Cookie")
        request.setValue("keep-alive", forHTTPHeaderField: "Connection")
        
        //
        request.writeToLogFile()
        
        // 创建并启动任务
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            MyMessage.hiddenWaitHUD()
            DispatchQueue.main.async {
                
                if let data = data, let responseString = String(data: data, encoding: .utf8) {
                    self.printWrite(log: "居民档案详情接口apiGetDetail返回->\(responseString)")
                    
                    let dic = responseString.toDic()
                    let httpCode = dic.intValue("code")
                    
                    if httpCode == 200{
                        let dataDic = dic.dictionary("data")
                        self.onGetArchivesDetailBlock?(true,dataDic)
                        
                    }else{
                        let httpErrorMsg = dic.strValue("message")
                        if self.isLoginExpiry(msg: httpErrorMsg) == true{
                            let log = "获取档案详情接口apiGetDetail发现登录过期 error:\(httpErrorMsg)）准备重新登录，登录成功后需重新调用该接口"
                            self.printWrite(log: log)
                            
                            self.onLoginSuccessBlock = {[weak self]in
                                guard let `self` = self else { return }
                                self.apiGetDetail(dataId: dataId, orgId: self.orgId, token: self.token, uuid: self.uuid, sid: self.sid)
                            }
                        }
                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
                    }
                    
                }else{
                    self.onGetArchivesDetailBlock?(false,[:])
                }
                
            }
            
        }
        task.resume()
    }
    
    
    /// 保存档案到云平台
    /// - Parameters:
    ///   - params: 档案数据
    ///   - token:
    ///   - uuid:
    ///   - sid:
    private func apiSaveArchivesToCloud(params:[String:Any],token:String,uuid:String,sid:String,onSaveArchivesBlock: ((_ re:Bool)->())?){
        
        let ipAddress = getIpAddress()
        let urlStr = "\(ipAddress)/ehrc/ehr/jkda/update"
        guard let url = URL(string: urlStr)else{return}
        var request = URLRequest(url: url)
        request.httpMethod = "PUT"
        
        let requestBody: [String: Any] = params
        guard let jsonData = try? JSONSerialization.data(withJSONObject: requestBody) else {
            print("Failed to serialize request body")
            return
        }
        request.httpBody = jsonData
        
        // 设置请求头
        request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue(ipAddress, forHTTPHeaderField: "Origin")
        request.setValue("OqBtDWuPpaQb6Z84q6HmQuSI3Y1WMBw0xf0bOsnBJdFzwFQhs0WIwS7DsOOMX5F1GZqA1ltMyoUKtjgnD9sesOUnWZTCylI12JhCvUP2bBm7ziho9pKDi+yzmeA2rvFJbEnwjaXQoMHvlrEQskj1hVMH9FE/OzzwiKcyEH9DIv/32sE9J7ePEPdC9JUafLd4NpA6GU4ErFtocBrlXHxAYrbQIda7lh1zxnODQmPogec=", forHTTPHeaderField: "Oow-Cjzwj-Kcow")
        request.setValue("heiCciT1Rmxftt2L", forHTTPHeaderField: "Ber-Cctpu-Qsax")
        request.setValue(token, forHTTPHeaderField: "accessToken")
        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        request.setValue("\(ipAddress)/index.html", forHTTPHeaderField: "Referer")
        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
        request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
        request.setValue("keep-alive", forHTTPHeaderField: "Connection")
        
        // 设置Cookie
        let cookieValue = "token=\(token); sid=\(sid); uuid=\(uuid)"
        request.setValue(cookieValue, forHTTPHeaderField: "Cookie")
        request.setValue("\(jsonData)", forHTTPHeaderField: "Content-Length")
        
        request.writeToLogFile()
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: request) {[weak self] data, response, error in
            MyMessage.hiddenWaitHUD()
            guard let `self` = self else { return }
            DispatchQueue.main.async {
                
                guard let data = data else{
                    if self.reSaveArchivesCount < 1{//重试一次
                        self.printWrite(log: "保存个人档案未返回成功或失败，自动重试一次")
                        self.reSaveArchivesCount += 1
                        self.apiSaveArchivesToCloud(params: params, token: self.token, uuid: self.uuid, sid: self.sid, onSaveArchivesBlock: onSaveArchivesBlock)
                    }
                    return
                }
                
                if let responseString = String(data: data, encoding: .utf8) {
                    self.printWrite(log: "保存居民档案接口apiSaveArchivesToCloud返回->\(responseString)")
                    let dic = responseString.toDic()
                    let httpCode = dic.intValue("code")
                    
                    if httpCode == 200{
                        onSaveArchivesBlock?(true)
                        
                    }else{
                        let httpErrorMsg = dic.strValue("message")
                        onSaveArchivesBlock?(false)
                        //登录过期
                        if self.isLoginExpiry(msg: httpErrorMsg){
                            let log = "编辑档案接口apiSaveArchivesToCloud发现登录过期 error:\(httpErrorMsg)）准备重新登录，登录成功后需重新调用该接口"
                            self.printWrite(log: log)
                            
                            self.onLoginSuccessBlock = {[weak self]in
                                guard let `self` = self else { return }
                                self.apiSaveArchivesToCloud(params: params, token: self.token, uuid: self.uuid, sid: self.sid, onSaveArchivesBlock: onSaveArchivesBlock)
                            }
                        }
                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
                    }
                    
                }
            }
            
        }
        task.resume()
        
    }
    
    
    /// 搜索云平台家庭列表
    /// - Parameters:
    ///   - token:
    ///   - uuid:
    ///   - sid:
    ///   - searchKey: 关键词
    ///   - searchType: 搜索类型
    private func apiGetFamilyList(token:String,uuid:String,sid:String,areaId:String,searchKey:String,searchType:CloudSearchEnum,finish:@escaping((_ re:Bool,_ familyList:[[String:Any]])->())) {
        let ipAddress = getIpAddress()
        let baseURL = "\(ipAddress)/ehrc/ehr/jkda/jt/get/paging/xjd"
        var urlComponents = URLComponents(string: baseURL)!
        
        urlComponents.queryItems = [
            URLQueryItem(name: "total", value: "0"),
            URLQueryItem(name: "pageNumber", value: "1"),
            URLQueryItem(name: "current", value: "1"),
            URLQueryItem(name: "pageSize", value: "16"),
            URLQueryItem(name: "isnull", value: "0"),
            URLQueryItem(name: "key", value: searchKey),
            URLQueryItem(name: "_type", value: "area"),
            URLQueryItem(name: "areaId", value: areaId),
            URLQueryItem(name: "rbh", value: areaId),
            URLQueryItem(name: "wgId", value: ""),
            URLQueryItem(name: "keyword", value: searchKey)]
        
        guard let url = urlComponents.url else {
            finish(false,[])
            return
        }
        
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
        request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        request.setValue(token, forHTTPHeaderField: "accessToken")
        request.setValue("keep-alive", forHTTPHeaderField: "Connection")
        request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.setValue("7lTInd7QOowSF4mf", forHTTPHeaderField: "Gec-Kipad-Gncm")
        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
        request.setValue("\(ipAddress)/jkda.html", forHTTPHeaderField: "Referer")
        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        request.setValue("jJgH4RdQ5ZbDSSCXLiaSgaBuJAVfWVTjEQJ1ZriuCH/LUtejsAIZ4uIw78bcdyWpOyxfCC/lVxQCf99zvRTH5Z1F+BsN7E9tUhvcRZZdk6kRdcOK8hjZVNEnCDk/9T8wTsHYDABeS2GWDZe6WKBE/vjrnf7nH8TD/MbLJycgHXy2YdxjOv4KwnVS3U8vw15rNvIuQbifENoGYb7KKP/nXfUPChljuiWiGqFX3uxS5YE=", forHTTPHeaderField: "Yay-Dviyv-Ldyy")
        
        let cookies = "sid=\(sid); token=\(token); uuid=\(uuid)"
        request.setValue(cookies, forHTTPHeaderField: "Cookie")
        
        request.writeToLogFile()
        
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: request) {[weak self] data, response, error in
            MyMessage.hiddenWaitHUD()
            guard let `self` = self else { return }
            DispatchQueue.main.async {
                
                guard let data = data else{
                    if self.reSearchFamilyCount < 1{//重试一次
                        self.printWrite(log: "搜索家庭档案列表请求获取数据为空，自动重试一次")
                        self.reSearchFamilyCount += 1
                        self.apiGetFamilyList(token: self.token, uuid: self.uuid, sid: self.sid, areaId: self.areaId, searchKey: searchKey, searchType: searchType, finish: finish)
                    }
                    return
                }
                
                if let responseString = String(data: data, encoding: .utf8) {
                    self.printWrite(log: "搜索云平台家庭列表apiGetFamilyList返回searchKey:\(searchKey)/\(searchType.rawValue)->\(responseString)")
                    
                    let dic = responseString.toDic()
                    let httpCode = dic.intValue("code")
                    
                    if httpCode == 200{
                        let dataArray = dic.dictionary("data").array("data")
                        finish(true,dataArray)
                        
                    }else{
                        let httpErrorMsg = dic.strValue("message")
                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
                        finish(false,[])
                    }
                    
                }else{
                    finish(false,[])
                }
            }
        }
        
        task.resume()
    }
    
    
    /// 获取家庭档案详情
    /// - Parameters:
    ///   - dataId: 数据ID
    ///   - orgId: 机构ID
    ///   - token: TOKEN
    ///   - uuid:
    ///   - sid:
    private func apiGetFamilyDetail(dataId:String,token:String,uuid:String,sid:String,finish:@escaping((_ re:Bool,_ familyDetail:[String:Any])->())) {
        
        let ipAddress = getIpAddress()
        let urlString = "\(ipAddress)/ehrc/ehr/jkda/jt/get/\(dataId)?"
        guard let url = URL(string: urlString) else {
            return
        }
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("application/json, text/plain, */*", forHTTPHeaderField: "Accept")
        request.setValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
        request.setValue(getAgbBatbaBbabString(), forHTTPHeaderField: "Agb-Batba-Bbab")
        request.setValue("", forHTTPHeaderField: "accessToken2")
        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        request.setValue("\(ipAddress)/index.html", forHTTPHeaderField: "Referer")
        request.setValue("KZEiL1Fncf64VB2N", forHTTPHeaderField: "E5o-Vt3gb-1aom")
        request.setValue(token, forHTTPHeaderField: "accessToken")
        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
        request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
        request.setValue("token=\(token); sid=\(sid); uuid=\(uuid)", forHTTPHeaderField: "Cookie")
        request.setValue("keep-alive", forHTTPHeaderField: "Connection")
        
        //
        request.writeToLogFile()
        
        // 创建并启动任务
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            MyMessage.hiddenWaitHUD()
            DispatchQueue.main.async {
                
                if let data = data, let responseString = String(data: data, encoding: .utf8) {
                    self.printWrite(log: "档案详情接口apiGetFamilyDetail返回->\(responseString)")
                    
                    let dic = responseString.toDic()
                    let httpCode = dic.intValue("code")
                    
                    if httpCode == 200{
                        let dataDic = dic.dictionary("data")
                        finish(true,dataDic)
                    }else{
                        let httpErrorMsg = dic.strValue("message")
                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
                        finish(false,[:])
                    }
                    
                }else{
                    finish(false,[:])
                }
                
            }
            
        }
        task.resume()
    }
    
    
    /// 获取图形验证码
    /// - Parameters:
    private func apiGetImageCode(appId:String,uuid:String,finish:@escaping((_ re:Bool,_ key:String,_ imgBase64:String)->())) {
        
        let ipAddress = getIpAddress()
        let urlString = "\(ipAddress)/ehrcportal/verifyCode/imageCode"
        guard let url = URL(string: urlString) else {
            return
        }
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        
        request.setValue("true", forHTTPHeaderField: "Access-Control-Allow-Credentials")
        request.setValue(getUserAgent(), forHTTPHeaderField: "User-Agent")
        request.setValue("*/*", forHTTPHeaderField: "Accept")
        request.setValue("1000", forHTTPHeaderField: "Access-Control-Max-Age")
        request.setValue("\(ipAddress)/portal/login.html?appId=\(appId)&isTop=true&redirectUri=\(ipAddress)/transferPage.html", forHTTPHeaderField: "Referer")
        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
        request.setValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
        request.setValue("uuid=\(uuid)", forHTTPHeaderField: "Cookie")
        request.setValue("keep-alive", forHTTPHeaderField: "Connection")
        
        request.writeToLogFile()
        
        // 创建并启动任务
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            MyMessage.hiddenWaitHUD()
            DispatchQueue.main.async {
                
                if let data = data, let responseString = String(data: data, encoding: .utf8) {
                    self.printWrite(log: "获取图形验证码接口返回->\(responseString)")
                    
                    let dic = responseString.toDic()
                    let httpCode = dic.intValue("code")
                    
                    if httpCode == 200{
                        let dataDic = dic.dictionary("data")
                        let imageCodeKey = dataDic.strValue("imageCodeKey")
                        let imgBase64 = dataDic.strValue("base64Str")
                        finish(true,imageCodeKey,imgBase64)
                        
                    }else{
                        let httpErrorMsg = dic.strValue("message")
                        self.alertOnError(msg: httpErrorMsg, httpCode: httpCode)
                        finish(false,"","")
                    }
                    
                }else{
                    finish(false,"","")
                }
            }
            
        }
        
        task.resume()
    }
    
    /// 获取图形验证码
    /// - Parameters:
    public func apiGetITTTTTTTTT() {
        
        let urlString = "https://support.weixin.qq.com/cgi-bin/mmsupportmeshnodelogicsvr-bin:14013/api/authorize"
        guard let url = URL(string: urlString) else {
            return
        }
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("*/*", forHTTPHeaderField: "Accept")
        request.setValue("gzip, deflate, br", forHTTPHeaderField: "Accept-Encoding")
        request.setValue("zh-CN,zh-Hans;q=0.9", forHTTPHeaderField: "Accept-Language")
        request.setValue("keep-alive", forHTTPHeaderField: "Connection")
        request.setValue("https://open.weixin.qq.com", forHTTPHeaderField: "Origin")
        request.setValue("u=3, i", forHTTPHeaderField: "Priority")
        request.setValue("https://open.weixin.qq.com/", forHTTPHeaderField: "Referer")
        request.setValue("empty", forHTTPHeaderField: "Sec-Fetch-Dest")
        request.setValue("cors", forHTTPHeaderField: "Sec-Fetch-Mode")
        request.setValue("same-site", forHTTPHeaderField: "Sec-Fetch-Site")
        request.setValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Safari/605.1.15", forHTTPHeaderField: "User-Agent")
                
        let params:[String:Any] = ["apiname":"qrconnectfastauthorize","jsdata":["data":"{\"x\":780,\"y\":433.5}","appid":"wx076ebeb2dc3d8f0f","scope":"snsapi_login","redirect_uri":"https://ehr.scwjxx.cn/portal/wxtransfer.html?appId=e860a5a1a6a940b49be5637cbe60181c&isTop=true&redirectUri=https%3A%2F%2Fehr.scwjxx.cn%2FtransferPage.html","state":"1","authorize_uuid":"09381Qpy37ms0w3O"]]
        
        if let jsonData = try? JSONSerialization.data(withJSONObject: params){
            request.httpBody = jsonData
        }
        
        
        request.writeToLogFile()
        
        // 创建并启动任务
        MyMessage.showWaitHUD()
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            MyMessage.hiddenWaitHUD()
            DispatchQueue.main.async {
                
                if let data = data, let responseString = String(data: data, encoding: .utf8) {
                    self.printWrite(log: "模拟微信扫码登录->\(responseString)")
                   
                    
                }else{
                    LogUtil.print(info: "模拟微信扫码登录失败")
                }
            }
            
        }
        
        task.resume()
    }
}
